package com.genymobile.scrcpy.five.cmd;

import com.genymobile.scrcpy.five.inject.FiveInjector;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public abstract class ICmd {
    public String context;
    public abstract boolean run(FiveInjector injector);
    abstract ICmd parse(long timestampMs, String[] arr);
    abstract String getCmdName();

    public long timestampMs;

    @Override
    public String toString() {
        return timestampMs + " " + getCmdName() + " ";
    }

    /**
     */
    private Field getFile(ICmd cmd, String fieldName) {
        Class<?> current = cmd.getClass();
        while (current != null) {
            try {
                return current.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                // 继续向父类查找
                current = current.getSuperclass();
            }
        }
        return null;
    }

    protected void setFiled(ICmd cmd, Field f, Object value) {
        try {
            Class<?> fieldType = f.getType();
            if (fieldType == int.class || fieldType == Integer.class) {
                f.set(cmd, value);
            } else if (fieldType == float.class || fieldType == Float.class) {
                f.set(cmd, value);
            } else if (fieldType == double.class || fieldType == Double.class) {
                f.set(cmd, value);
            } else {
                f.set(cmd, value);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    protected void parseAndSet(String line, ICmd cmd) {
        String[] tmp = line.split("=");
//        System.out.println("line=" + line + " splitArr=" + tmp);
        if (tmp.length == 2) {
            String key = tmp[0];
            String value = tmp[1];
            Field f = getFile(cmd, key);
//            System.out.println("line=" + line + " f=" + f);
            if (f == null) {
                return;
            }
            Class<?> fieldType = f.getType();
            if (fieldType == int.class || fieldType == Integer.class) {
                setFiled(cmd, f, Integer.parseInt(value));
            } else if (fieldType == float.class || fieldType == Float.class) {
                setFiled(cmd, f, Float.parseFloat(value));
            } else if (fieldType == double.class || fieldType == Double.class) {
                setFiled(cmd, f, Double.parseDouble(value));
            } else if (fieldType == String.class) {
                setFiled(cmd, f, value);
            }
        }
    }
}
